﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Web.Script.Serialization;

namespace jQuery.Treeview
{
    public partial class PageMethodServer : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        { }

        [System.Web.Services.WebMethod]
        [System.Web.Script.Services.ScriptMethod(UseHttpGet = true)]
        public static void FileSystemInfos()
        {
            string root = HttpContext.Current.Request.Params.Get("root");
            int? nodeId = (root == "source") ? (int?)null : Convert.ToInt32(root);
            IEnumerable<FileSystemInfo> children = FileSystemInfosRepository.GetFileSystemInfos(nodeId);

            List<TreeViewNode> nodes = new List<TreeViewNode>();
            foreach (FileSystemInfo child in children)
            {
                bool leaf = child is FileInfo;
                nodes.Add(new TreeViewNode()
                {
                    id = Convert.ToString(FileSystemInfosRepository.GetNodeId(child)),
                    text = child.Name,
                    classes = leaf ? "file" : "folder",
                    hasChildren = !leaf
                });
            }

            JavaScriptSerializer serializer = new JavaScriptSerializer();
            string nodesSerialized = serializer.Serialize(nodes);

            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.ContentType = "application/json; charset=utf-8";
            HttpContext.Current.Response.AddHeader("Content-Length", nodesSerialized.Length.ToString());
            HttpContext.Current.Response.AddHeader("Connection", "Close");
            HttpContext.Current.Response.Write(nodesSerialized);
            HttpContext.Current.Response.Flush();
        }
    }
}